package factory.one.service;

import factory.one.Application;
import factory.one.entity.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author sk.z
 * 2023/6/26
 * 数据库初始化
 **/
@Component
public class DatabaseInit {

    private final static Logger logger = LoggerFactory.getLogger(Application.class);
    private final DatabaseService databaseService;
    private final JdbcTemplate jdbcTemplate;

    public DatabaseInit(DatabaseService databaseService,
                        JdbcTemplate jdbcTemplate) {
        this.databaseService = databaseService;
        this.jdbcTemplate = jdbcTemplate;
    }

    @PostConstruct
    private void init() {
        logger.info("init database.");

        List<SysTable> userTables = databaseService.getUserTables();
        if (CollectionUtils.isEmpty(userTables)) {
            baseData();
        } else {
            updatePath();
        }
    }

    //空库初始化
    private void baseData() {
        int baseVersion = 4;
        jdbcTemplate.execute(Batch.CREATE_SQL);
        jdbcTemplate.execute(Custom.CREATE_SQL);
        jdbcTemplate.execute(Deliver.CREATE_SQL);
        jdbcTemplate.execute(Deliver.INDEX1_SQL);
        jdbcTemplate.execute(DeliverItem.CREATE_SQL);
        jdbcTemplate.execute(DeliverItem.INDEX1_SQL);
        jdbcTemplate.execute(IUser.CREATE_SQL);
        jdbcTemplate.execute(Money.CREATE_SQL);
        jdbcTemplate.execute(Order.CREATE_SQL);
        jdbcTemplate.execute(OrderSequence.CREATE_SQL);
        jdbcTemplate.execute(Product.CREATE_SQL);
        jdbcTemplate.execute(Refund.CREATE_SQL);
        //jdbcTemplate.execute(Send.CREATE_SQL); 发货交互修改 此结构废弃 数据保留 20231108
        jdbcTemplate.execute(Version.CREATE_SQL);
        // admin / admin
        jdbcTemplate.update("insert into users (user_name, password, authorities, enabled) values ('admin','$2a$04$Lhq6fRCHgLvV7AviNHUPQ.cTfAhz/EhlFciikM8xgwxm/pE487xwm','ADMIN',true)");
        // db version
        jdbcTemplate.update("insert into version (id, version) values ('db'," + baseVersion + ")");
    }

    //升级补丁
    private void updatePath() {
        List<Integer> versionList = jdbcTemplate.query("select version from version where id = 'db'", (rs, rowNum) -> rs.getInt(1));
        Integer curVersion = versionList.get(0);
        logger.info("当前数据库版本为:[{}]", curVersion);

        if (curVersion < 1) {
            jdbcTemplate.execute(Refund.CREATE_SQL);
            jdbcTemplate.update("ALTER TABLE \"ORDER\" ADD COLUMN REFUND_NUM INT NOT NULL DEFAULT 0");
            jdbcTemplate.update("ALTER TABLE BATCH ADD COLUMN REFUND_NUM INT NOT NULL DEFAULT 0");
            updateVersion(1);
        }
        if (curVersion < 2){
            jdbcTemplate.execute(Money.CREATE_SQL);
            jdbcTemplate.execute("ALTER TABLE \"ORDER\" ADD COLUMN CONTRACT_AMOUNT bigint not null default 0");
            jdbcTemplate.execute("ALTER TABLE \"ORDER\" ADD COLUMN ACTUAL_AMOUNT bigint not null default 0");
            updateVersion(2);
        }
        if (curVersion < 3){
            jdbcTemplate.execute("ALTER TABLE CUSTOM ADD COLUMN CREATE_USER varchar(32) not null default ''");
            updateVersion(3);
        }
        if (curVersion < 4){
            jdbcTemplate.execute(Deliver.CREATE_SQL);
            jdbcTemplate.execute(Deliver.INDEX1_SQL);
            jdbcTemplate.execute(DeliverItem.CREATE_SQL);
            jdbcTemplate.execute(DeliverItem.INDEX1_SQL);
            updateVersion(4);
        }
    }

    private void updateVersion(int version) {
        jdbcTemplate.update("update version set version = ? where id = 'db'", version);
    }

    private void resetData() {
        //管理员帐户
        List<String> list = jdbcTemplate.query("select user_name from users where user_name = 'admin'", (rs, rowNum) -> rs.getString(1));
        if (CollectionUtils.isEmpty(list)) {
            jdbcTemplate.update("insert into users (user_name, password, authorities, enabled) values ('admin','$2a$04$Lhq6fRCHgLvV7AviNHUPQ.cTfAhz/EhlFciikM8xgwxm/pE487xwm','ADMIN',true)");
        }
        //jdbcTemplate.update("update users set password='$2a$04$Lhq6fRCHgLvV7AviNHUPQ.cTfAhz/EhlFciikM8xgwxm/pE487xwm' where user_name='admin' ");
    }

}
